//
//  AMEditView.m
//  WeiDu_1_0
//
//  Created by foguo-mac-1 on 01/07/16.
//  Copyright (c) 2016 WeiDu Energy Tech. All rights reserved.
//

#import "HOEditView.h"
#import "Logger.h"
#import "HOUtils.h"
@implementation HOLimitedEditView
@synthesize placeHolder;
- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
//	self.layer.borderWidth = 1;
    if(self.text.length == 0 && self.placeHolder != nil)
    {
        UIColor* color = TEXT_COLOR_999999;       //create color
        [color set];                                //set color
        if(IS_LESSTHAN_IOS7)
        {
            [self.placeHolder drawAtPoint:CGPointMake(HO_HORIZONAL_PADDING, 8) withFont:[UIFont systemFontOfSize:CELL_FONT_SIZE]];
        }
        else
        {
            
            [self.placeHolder drawAtPoint:CGPointMake(HO_HORIZONAL_PADDING, 8) withAttributes:@{NSForegroundColorAttributeName:UIColorFromRGB(0x888888),NSFontAttributeName:[UIFont systemFontOfSize:CELL_FONT_SIZE]} ];
        }
    }
}

@end


@implementation HOEditView
@synthesize limitedCount = _limitedCount;
@synthesize delegate;
@synthesize placeHolder = _placeHolder;

//- (instancetype)init
//{
//    if(self = [super init])
//    {
//        inputBox = [[HOLimitedEditView alloc] init];
//        inputCountCalLbl = [[UILabel alloc] init];
//        inputCountCalLbl.font = [UIFont systemFontOfSize:12];
//        
//        inputBox.layer.borderWidth = 2;
//        //        inputCountCalLbl.layer.borderWidth = 1;
//        [self addSubview:inputBox];
//        [self addSubview:inputCountCalLbl];
//    }
//    return self;
//}


- (id)initWithFrame:(CGRect)frame
{
    if(self = [super initWithFrame:frame])
    {
        inputBox = [[HOLimitedEditView alloc] initWithFrame:CGRectMake(0,
                                                                0,
                                                                frame.size.width,
                                                                frame.size.height)];
//        inputBox.layer.borderWidth = 1;
        inputCountCalLbl = [[UILabel alloc]init];
        [self setBackgroundColor:[UIColor whiteColor]];
        inputCountCalLbl.frame = CGRectMake(frame.size.width - 58,
                                      frame.size.height - 30,
                                      50,
                                      22);
        [inputCountCalLbl setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:.5]];
        inputCountCalLbl.layer.cornerRadius = 2;
		inputCountCalLbl.hidden = YES;
        [inputCountCalLbl.layer setMasksToBounds:YES];
        inputCountCalLbl.textAlignment = NSTextAlignmentCenter;
        inputCountCalLbl.text = @"23/233";
        inputBox.font = [UIFont systemFontOfSize:15];
        
        inputCountCalLbl.font = [UIFont systemFontOfSize:12];
        inputCountCalLbl.textColor = [UIColor whiteColor];
        inputBox.autoresizingMask = YES;
        inputBox.delegate = self;
        inputBox.returnKeyType = UIReturnKeyDefault;
        self.layer.borderWidth = [HOUtils  defaultOnePixelConversion];
        self.layer.borderColor = UIColorFromRGB(0xdcdcdc).CGColor;
//        inputBox.layer.cornerRadius = 5;
        
//        inputBox.text = @"fdsjfklaj fdsakl fjdasklj f;a jfdk;lasj kf;ld aj;f djsa;jd f;laj f;dasj f;dsajklf djaksl fd;sakj fd;as fdsjfklaj fdsakl fjdasklj f;a jfdk;lasj kf;ld aj;f djsa;jd f;laj f;dasj f;dsajklf djaksl fd;sakj fd;as fdsjfklaj fdsakl fjdasklj f;a jfdk;lasj kf;ld aj;f djsa;jd f;laj f;dasj f;dsajklf djaksl fd;sakj fd;as fdsjfklaj fdsakl fjdasklj f;a jfdk;lasj kf;ld aj;f djsa;jd f;laj f;dasj f;dsajklf djaksl fd;sakj fd;as fdsjfklaj fdsakl fjdasklj f;a jfdk;lasj kf;ld aj;f djsa;jd f;laj f;dasj f;dsajklf djaksl fd;sakj fd;as fdsjfklaj fdsakl fjdasklj f;a jfdk;lasj kf;ld aj;f djsa;jd f;laj f;dasj f;dsajklf djaksl fd;sakj fd;as ";
        inputBox.scrollsToTop = YES;
        [self addSubview:inputBox];
        [self addSubview:inputCountCalLbl];
    }
    return self;
}

- (void)updateLayout
{
	inputBox.frame = CGRectMake(0,
																   0,
																   self.frame.size.width,
																   self.frame.size.height);
}

- (BOOL)becomeFirstResponder
{
    return [inputBox becomeFirstResponder];
}

- (void)setPlaceHolder:(NSString *)placeHolder
{
    inputBox.placeHolder = placeHolder;
    [inputBox setNeedsDisplay];
}

- (NSString *)getText
{
    return inputBox.text;
}

- (UITextView *)getTextView
{
    return inputBox;
}
- (void)setText:(NSString *)text
{
    inputBox.text = text;
    inputCountCalLbl.text = [NSString stringWithFormat:@"%d/%d", (int)text.length, _limitedCount];
}
- (void)setKeyboardType:(UIKeyboardType)type
{
    inputBox.keyboardType = type;
}
- (void)hideLimitedCountView
{
    inputCountCalLbl.hidden = YES;
}


- (void)setLimitedCount:(int)limitedCount
{
    _limitedCount = limitedCount;
    
    inputCountCalLbl.text = [NSString stringWithFormat:@"0/%d", _limitedCount];
}

//-----过滤字符串中的emoji
- (NSString *)disable_emoji:(NSString *)text {
	NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]"options:NSRegularExpressionCaseInsensitive error:nil];
	NSString *modifiedString = [regex stringByReplacingMatchesInString:text
															   options:0
																 range:NSMakeRange(0, [text length])
														  withTemplate:@""];
	return modifiedString;
}

/**
 * 判断 字母、数字、中文
 */
- (BOOL)isInputRuleAndNumber:(NSString *)str
{
	NSString *other = @"➋➌➍➎➏➐➑➒";     //九宫格的输入值
	unsigned long len=str.length;
	for(int i=0;i<len;i++)
	{
		unichar a=[str characterAtIndex:i];
		if(!((isalpha(a))
			 ||(isalnum(a))
			 //             ||((a=='_') || (a == '-')) //判断是否允许下划线，昵称可能会用上
			 ||((a==' '))                 //判断是否允许空格
			 ||((a >= 0x4e00 && a <= 0x9fa6))
			 ||([other rangeOfString:str].location != NSNotFound)
			 ))
			return NO;
	}
	return YES;
}

/**
 判断是不是九宫格
 @param string  输入的字符
 @return YES(是九宫格拼音键盘)
 */
-(BOOL)isNineKeyBoard:(NSString *)string
{
	NSString *other = @"➋➌➍➎➏➐➑➒";
	int len = (int)string.length;
	for(int i=0;i<len;i++)
	{
		if(!([other rangeOfString:string].location != NSNotFound))
			return NO;
	}
	return YES;
}

/**
 *  判断字符串中是否存在emoji
 * @param string 字符串
 * @return YES(含有表情)
 */
- (BOOL)stringContainsEmoji:(NSString *)string {
	
	__block BOOL returnValue = NO;
	
	[string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
	 ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
		 
		 const unichar hs = [substring characterAtIndex:0];
		 // surrogate pair
		 if (0xd800 <= hs && hs <= 0xdbff) {
			 if (substring.length > 1) {
				 const unichar ls = [substring characterAtIndex:1];
				 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
				 if (0x1d000 <= uc && uc <= 0x1f77f) {
					 returnValue = YES;
				 }
			 }
		 } else if (substring.length > 1) {
			 const unichar ls = [substring characterAtIndex:1];
			 if (ls == 0x20e3) {
				 returnValue = YES;
			 }
			 
		 } else {
			 // non surrogate
			 if (0x2100 <= hs && hs <= 0x27ff) {
				 returnValue = YES;
			 } else if (0x2B05 <= hs && hs <= 0x2b07) {
				 returnValue = YES;
			 } else if (0x2934 <= hs && hs <= 0x2935) {
				 returnValue = YES;
			 } else if (0x3297 <= hs && hs <= 0x3299) {
				 returnValue = YES;
			 } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
				 returnValue = YES;
			 }
		 }
	 }];
	
	return returnValue;
}
/**
 *  判断字符串中是否存在emoji
 * @param string 字符串
 * @return YES(含有表情)
 */
- (BOOL)hasEmoji:(NSString*)string;
{
	NSString *pattern = @"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]";
	NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
	BOOL isMatch = [pred evaluateWithObject:string];
	return isMatch;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
		if([self.delegate respondsToSelector:@selector(sendNow:)])
		{
			[self.delegate sendNow:self];
		}
        return NO;
    }
	if ([[[textView textInputMode] primaryLanguage] isEqualToString:@"emoji"] || ![[textView textInputMode] primaryLanguage]) {
		return NO;
	}
	

    [textView setNeedsDisplay];
    NSUInteger newLength=0;
    if (range.length<=[textView.text length]+[text length]) {
        newLength = [textView.text length] + [text length] - range.length;
    }
    if([text length] == 0)
        return YES;
    if((newLength > _limitedCount) )
    {
        if (_limitedCount > textView.text.length||
            (_limitedCount == textView.text.length&&range.length>0)) {
            NSString *firstStr = [textView.text substringToIndex:textView.selectedRange.location];
            NSString *secondStr = [textView.text substringFromIndex:textView.selectedRange.location];
            if (firstStr.length+text.length > _limitedCount) {
                NSString *str = [text substringToIndex:_limitedCount - firstStr.length];
                textView.text = [NSString stringWithFormat:@"%@%@",firstStr,str];
            }else
            {
                textView.selectedRange =range;
                if (firstStr.length+text.length+secondStr.length > _limitedCount) {
                    NSString *str = [secondStr substringToIndex:_limitedCount - text.length-firstStr.length];
                    textView.text = [NSString stringWithFormat:@"%@%@%@",firstStr,text,str];
                }
            }
            
        }
        [self limitedTextDidChange:(int)textView.text.length];
        return NO;
    }
	
	//判断键盘是不是九宫格键盘
	if ([self isNineKeyBoard:text] )
	{
		return YES;
	}else
	{
		if ([self hasEmoji:text] || [self stringContainsEmoji:text])
		{
			return NO;
		}
	}
		
    return YES;
}



- (void)textViewDidChange:(UITextView *)textView
{
//    LogNor(@"textViewDidChange");
    NSString *toBeString = textView.text;
    if (toBeString.length > _limitedCount) {
    }
    int count = (int)textView.text.length;
    [self limitedTextDidChange:count];
    [inputBox setNeedsDisplay];
}
- (void)limitedTextDidChange:(int)count
{
    
//    LogInf(@"count:%d limitedCount:%d", count, _limitedCount);
    inputCountCalLbl.text = [NSString stringWithFormat:@"%d/%d", count, _limitedCount];
    if(count > _limitedCount)
    {
        [self.delegate popupHintView:[NSString stringWithFormat:@"字数超界%d个, 请控制字数!", count - _limitedCount]];
        inputCountCalLbl.textColor = [UIColor redColor];
    }
    else
    {
        inputCountCalLbl.textColor = [UIColor whiteColor];
        
        [self.delegate hideHintView];
    }
}


//- (void)submitComment
//{
//    
//    [self resignFirstResponder];
//    NSString *comment = [[self text] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//    
//    if(comment.length > 0)
//    {
//        if(comment.length > limitedCount)
//        {
//            comment = [comment substringFromIndex:limitedCount];
//            
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
//                                                            message:@"您输入的字数超过140个，请控制字数!"
//                                                           delegate:self
//                                                  cancelButtonTitle:@"关闭"
//                                                  otherButtonTitles:nil, nil];
//            [alert show];
//            [alert release];
//            //            return;
//        }
//        else
//        {
//        }
//    }
//    
//    
//}

- (void)dealloc
{
	[HOUtils removeFromSuperViewForViews:inputBox, inputCountCalLbl];
    self.delegate = nil;
    [inputBox release];
    inputBox = nil;
    [inputCountCalLbl release];
    inputCountCalLbl = nil;
    
    [super dealloc];
}

@end
